package com.tsfyun.common.base.config;

import com.tsfyun.common.base.enums.ResultCodeEnum;
import com.tsfyun.common.base.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.Objects;
import java.util.Set;

/**
 * @Description: 校验配置
 * @Project:
 * @CreateDate: Created in 2019-06-14 14:21
 */


@Component
public class ValidationUtil {


    @Autowired
    private Validator validator;


    public <T> void validate(T t, Class<?>... group) {
        Set<ConstraintViolation<T>> validateSet = validateData(t, group);
        if (!CollectionUtils.isEmpty(validateSet)) {
            String messages = validateSet.stream()
                    .map(ConstraintViolation::getMessage)
                    .reduce((m1, m2) -> m1 + "；" + m2)
                    .orElse("参数输入有误！");
            throw new ServiceException(ResultCodeEnum.PARAMS_IS_INVALID.getCode(), messages);
        }
    }


    public <T> Set<ConstraintViolation<T>> validateData(T t, Class<?>... group) {

        //校验不加group的校验注解
        Set<ConstraintViolation<T>> validateSet = validator
                .validate(t);

        //校验对应group的校验注解
        if (!Objects.isNull(group)) {
            Set<ConstraintViolation<T>> validate = validator
                    .validate(t, group);

            validateSet.addAll(validate);
        }
        return validateSet;
    }

}
